#include <cmath>
#include "manager.h"
#include "spriteFactory.h"
#include "multiSpriteFactory.h"
#include "sprite.h"

Manager::~Manager() {
	// These deletions eliminate "definitely lost" and
	// "still reachable"s in Valgrind.
	delete io;
	delete SpriteFrameFactory::getInstance();
	delete gdata;
	delete view;
	delete doodle;
	delete steps;
}

Manager::Manager() :
		env(SDL_putenv(const_cast<char*>("SDL_VIDEO_CENTERED=center"))), gdata(
				Gamedata::getInstance()), io(IOManager::getInstance()), clock(), screen(
				io->getScreen()), clouds(
				SpriteFrameFactory::getInstance()->getFrame("back", "back"), 1), view(
				Viewport::getInstance()), doodle(NULL) {
	if (SDL_Init(SDL_INIT_VIDEO) != 0) {
		throw string("Unable to initialize SDL: ");
	}

	Vector2f position(gdata->getXmlInt("doodleRightX"), gdata->getXmlInt("doodleRightY"));
	Vector2f velocity(gdata->getXmlInt("doodleRightXspeed"),
			gdata->getXmlInt("doodleRightYspeed"));
//  doodle = new MultiSprite(position, velocity,
//            MultiSpriteFrameFactory::getInstance()->getFrame("doodle","doodle"),
//             "doodle");
	Frame* f = SpriteFrameFactory::getInstance()->getFrame("doodleRight", "doodleRight");
	Frame* left = SpriteFrameFactory::getInstance()->getFrame("doodleLeft", "doodleLeft");
	doodle = new DoodleSprite(position, velocity, f, left);
	steps = new Steps(doodle);
	view->setObjectToTrack(doodle);
	atexit(SDL_Quit);
}

void Manager::update() {
	Uint32 ticks = clock.getElapsedTicks();
	steps->update(ticks);
	doodle->update(ticks);
	view->update();
	clouds.update();
}

void Manager::draw() const {

	clouds.draw();
	steps->draw();
	view->draw();
	doodle->draw();
	//orbs.draw();

}

void Manager::play() {
	SDL_Event event;

	bool done = false;
	bool keyCatch = false;
	while (not done) {
		draw();
		SDL_Flip(screen);
		update();

		SDL_PollEvent(&event);
		Uint8 *keystate = SDL_GetKeyState(NULL);
		if (event.type == SDL_QUIT) {
			break;
		}
		if (event.type == SDL_KEYUP) {
			keyCatch = false;
		}
		if (event.type == SDL_KEYDOWN) {
			switch (event.key.keysym.sym) {
			case SDLK_ESCAPE:
				done = true;
				break;
			case SDLK_q:
				done = true;
				break;

			case SDLK_LEFT:
				doodle->moveLeft();
				break;
			case SDLK_RIGHT:
				doodle->moveRight();
				break;
			case SDLK_UP:
				doodle->jump();
				break; // Cheat code!!!

			case SDLK_p: {
				if (!keyCatch) {
					keyCatch = true;
					if (clock.isPaused())
						clock.unpause();
					else
						clock.pause();
				}
				break;
			}
			default:
				break;
			}
		}
	}
}
